package com.wk.warehouse.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.wk.warehouse.entity.*;
import com.wk.warehouse.service.*;
import com.wk.warehouse.page.Page;
import com.wk.warehouse.util.CurrentUser;
import com.wk.warehouse.util.TokenUtils;
import com.wk.warehouse.util.WarehouseConstants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/product")
public class ProductController {
	
	@Autowired
	ProductService productService;
	@Autowired
	StoreService storeService;
	@Autowired
	BrandService brandService;
	@Autowired
	ProductCategoryService productCategoryService;
	@Autowired
	UnitService unitService;
	@Autowired
	PlaceService placeService;
	@Autowired
	SupplyService supplyService;
	// 获取配置文件的属性
	@Value("${file.upload-path}")
	private String uploadPath;

	/**
	 * 所有仓库
	 */
	@GetMapping("/store-list")
	public Result storeList() {
		return Result.ok(storeService.storeList());
	}

	/**
	 * 所有品牌
	 */
	@GetMapping("/brand-list")
	public Result brandList() {
		return Result.ok(brandService.selectAllBrand());
	}

	/**
	 * 所有分类，分层结构
	 */
	@GetMapping("/category-tree")
	public Result categoryTree() {

		return Result.ok(productCategoryService.findTypeTree());
	}

	/**
	 * 所有供应商
	 */
	@GetMapping("/supply-list")
	public Result supplyList() {
		return Result.ok(supplyService.findAll());
	}

	/**
	 * 所有产地
	 */
	@GetMapping("/place-list")
	public Result placeList() {
		return Result.ok(placeService.findAll());
	}

	/**
	 * 所有单位
	 */
	@GetMapping("/unit-list")
	public Result unitList() {
		return Result.ok(unitService.selectUnitList());
	}

	/**
	 * 分页模糊查询所有商品
	 */
	@GetMapping("/product-page-list")
	public Result productPageList(Product product, Page page){
		// 获取总条数
		int totalNum = productService.selectCount(product);
		page.setTotalNum(totalNum);

		// 查询商品信息
		List<Product> productList = productService.selectProductMess(product, page);
		page.setResultList(productList);
		return Result.ok(page);
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/exportTable")
	public Result exportTable(Product product, Page page){
		page = new Page(9999, 1); // 导出模糊查询所有数据
		// 要导出的数据
		List<Product> productList = productService.selectProductMess(product, page);
		return Result.ok(productList);
	}
	
	/**
	 * 修改商品
	 */
	@PutMapping("/product-update")
	public Result updateProduct(@RequestBody Product product, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken){
		// 获取修改人id
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		int updateBy = currentUser.getUserId();
		product.setUpdateBy(updateBy);
		// 图片
		if(product.getImgs()!=null && product.getImgs()!="" && !product.getImgs().startsWith(uploadPath)){
			// 修改了图片
			product.setImgs(uploadPath + "/" + product.getImgs());
		}
		System.out.println(product);
		productService.updateProduct(product);
		return Result.ok("修改商品成功！");
	}
	
	/**
	 * 上传图片
	 */
	@PostMapping("/img-upload")
	public Result upLoadImg(@RequestParam("file") MultipartFile image) {
		System.out.println("上传图片");
		// 上传路径设置
		// https://www.cnblogs.com/yuluoxingkong/p/11576676.html
		if (!image.isEmpty()) {
            try {
				// 文件上传目录
				File uploadDir = new File(uploadPath);
				if(!uploadDir.exists()) uploadDir.mkdirs();
                // 文件保存路径
                String filePath = uploadDir.getAbsolutePath() + File.separator + image.getOriginalFilename();
                // 保存图片
				image.transferTo(new File(filePath));
				return Result.ok();
            } catch (Exception e) {
                e.printStackTrace();
            }  
        }
		return null;
	}
	
	/**
	 * 添加商品
	 */
	@PostMapping("/product-add")
	public Result addProduct(@RequestBody Product product, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken){
		// 获取添加人id
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		int createBy = currentUser.getUserId();
		product.setCreateBy(createBy);
		// 图片
		if(product.getImgs()!=null && product.getImgs()!=""){
			product.setImgs(uploadPath + "/" + product.getImgs());
		}
		productService.addProduct(product);
		return Result.ok("添加商品成功！");
	}
	
	/**
	 * 改变上下架状态
	 */
	@PutMapping("/state-change")
	public Result changeState(@RequestBody Product product){
		productService.changeState(product);
		return Result.ok(product.getUpDownState().equals("0")?"下架成功!":"上架成功！");
	}

	/**
	 * 删除单个商品
	 */
	@DeleteMapping("/product-delete/{productId}")
	public Result deleteProduct(@PathVariable Integer productId){
		productService.deleteProduct(productId);
		return Result.ok("删除商品成功！");
	}

	/**
	 * 删除多个商品
	 */
	@DeleteMapping("/product-list-delete")
	public Result deleteProductList(@RequestBody List<Integer> productIds){
		productService.deleteProducts(productIds);
		return Result.ok("删除商品成功！");
	}
}
